package com.enzoism.mvc.controller;

import cn.hutool.http.HttpRequest;
import com.enzoism.mvc.common.Constants;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.net.URI;

/**
 * 使用当前方法调用【一言】官网
 */
@RestController
public class RequestController {

    @GetMapping(value = "hutool")
    public String urlRequestByHutool() {
        String result = HttpRequest.get(Constants.OTHER_URL).timeout(20000).execute().body();
        return result;
    }


    @Autowired
    RestTemplate restTemplate;

    @SneakyThrows
    @GetMapping(value = "rest")
    public String restTemplate() {
        String result = restTemplate.getForObject(new URI(Constants.OTHER_URL), String.class);
        return result;
    }

    @SneakyThrows
    @GetMapping(value = "webflux")
    public String webFlux() {
        Flux<String> stringFlux = WebClient.create()
                //调用方式 post
                .get().uri(Constants.OTHER_URL)
                //调用
                .retrieve()
                //返参类型Mono / Flux
                //使用Mono和Flux接收返回结果，一个Mono对象包含0个或1个元素，而一个Flux对象包含1个或多个元素
                .bodyToFlux(String.class);
        //阻塞式获取结果，subscribe()为非阻塞
        String result = stringFlux.blockFirst();
        return result;
    }

}
